package pl.kech.pszczyna.repository;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import pl.kech.pszczyna.domain.Image;
import pl.kech.pszczyna.web.Utils;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;

@Repository
public class ImageDAOImpl extends GenericDAOImpl<Image> implements ImageDAO {
	
	@Autowired
	private BlobstoreService blobstoreService;
	
	@Override
	public Long deleteAndReturnGalleryCatId(final Object id){
		Image img = find(id);
		blobstoreService.delete(Utils.createBlobKey(img.getBlobKeyStr()));
		delete(id);
		return img.getGalleryCatId();
	}
	
	@Override
	public void uploadImage(Long galleryCatId, HttpServletRequest request) {
		Map<String, BlobKey> blobs = blobstoreService.getUploadedBlobs(request);
        BlobKey blobKey = blobs.get("myFile");
        if (blobKey == null) {
            throw new IllegalArgumentException("blobKey is null");
        } 
        Image img = new Image(blobKey.getKeyString());
        img.setGalleryCatId(galleryCatId);
        create(img);
	}
	
	@Override
	public void getImage(String blobKeyStr, HttpServletResponse response) throws IOException {
		BlobKey blobKey = Utils.createBlobKey(blobKeyStr);
        blobstoreService.serve(blobKey, response);
	}

}
